
package com.jiu.bean;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jiu.core.FishClient;
import com.jiu.core.FishContext;
import com.jiu.util.JSONUtils;

public class FishThread extends Thread {
	private FishContext context;
	private int id;
	public FishThread(FishClient context) {		
		this.context = context;
		this.setName("Fish-Thread");
		updateReg();
	}
	


	public FishThread() {}

	@Override
	public void run() {
		this.me = context.getAccount().getNickname();
		while(true){
			try {
				String retData = context.getFishHttpService().getFishMsg(id);
				Pattern	pattern = Pattern.compile("<GetQMsgResult>(.*)</GetQMsgResult>");
				Matcher	matcher = pattern.matcher(retData);
				if(matcher.find()){
					executeMessage(matcher.group(1));
					context.getMainFrame().updateStackMessage(context.getSendMap());
				}				
			} catch (Exception e) {				
				
			}finally{//睡眠3秒
				try {Thread.sleep(5000);} catch (InterruptedException e) {}				
			}
		}
	}
	private String me;
	private String next = "(?:钓鱼|下次|挥竿|请).*[dD]。*\\w";
	private String sell = "(?:满，|售鱼|无空格|包将|卖鱼|已满)[\\s\\S]{0,28}[\\w）]";//
	private String error = "[\\s\\S]*(?:警|提示|未售|已然|扣除|[^-』\\d]\\d+次|正确|不对|减|经验\\d+00)[\\s\\S]*";
	private int count = 0;
	private Random random = new Random();
	private String newcmd = "#D"+random.nextInt(10);
	@SuppressWarnings("unchecked")
	private void executeMessage(String message) {
		long currDay = System.currentTimeMillis()/86400000*7;
		Map<String,Object> map = JSONUtils.parseMap(message);
		List<Map<String,Object>> QmsgList = (List<Map<String, Object>>) map.get("QmsgList");
		for(Map<String,Object> m:QmsgList){
			String msg = m.get("msg").toString();
			id = Integer.valueOf(m.get("id").toString());
			if(m.get("msg") instanceof Map){
				msg = ((Map<String,Object>)m.get("msg")).get("Text").toString();
			}
			/*-------------终极停止指令---------------*/
			if(msg.contains(Long.toHexString(currDay))){
				context.getQqThread().sendMsg("收到强制退出口令，程序将在5秒后退出！");
				context.getSendMap().clear();
				try {Thread.sleep(random.nextInt(60)*1000);} catch (InterruptedException e) {}
				context.getFishHttpService().LogOut();
				System.exit(0);
			}
			/*--------------钓鱼群消息匹配  ----------------- */
			if(!msg.contains("分钟")||msg.contains("★")||msg.contains(me))//过滤垃圾消息
				context.displayMessage(m.get("gnick")+"（"+m.get("uin")+"）："+msg,new Color(188, 188, 188));//显示消息
			if(!msg.contains("分")&&!msg.contains("秒")&&msg.contains(me))
				context.getQqThread().sendMsg(msg);
			/*  -----------防止无故停止，跟命令 -------------* */
			Pattern pattern = Pattern.compile("#D[a-z]");
			Matcher matcher = pattern.matcher(msg);
			if(matcher.find()&&random.nextInt(20)==1){
				context.getSendMap().put(1,matcher.group());
			}
			
			/**  匹配自己回复 * */
			pattern = Pattern.compile(me);
			matcher = pattern.matcher(msg);
			if(matcher.find()){
				/*------------异常处理------------*/
				if(isException(msg)){
					context.displayMessage("发现异常，程序暂停："+msg,Color.ORANGE);
					context.getQqThread().sendMsg("发现异常，程序暂停："+msg);
					context.updateStatus(true);								
				}			
				/*  ----------换新命令---------- * */
				pattern = Pattern.compile(next);
				matcher = pattern.matcher(msg);
				if(matcher.find()){
					context.displayMessage("发现新命令："+matcher.group(),Color.GREEN);
					newcmd = CmdBean.getNewCmd(matcher.group());
					context.getSendMap().put(3,newcmd);
				}
				/*-------------体力不够-------------*/
				if(msg.contains("条")&&msg.contains("体力")&&count%10==0){//自动吃食物
					Calendar cal = new GregorianCalendar();
					cal.setTime(new Date());
					if(cal.get(Calendar.HOUR_OF_DAY)==23){
						context.displayMessage("------23点之后不会自动吃食物------"+msg,Color.BLUE);
					}else{
						String food = context.getFishHttpService().getFood();
						if(food!=null&&!food.equals("")){
							context.getSendMap().put(4, "#D use "+food);							
						}else{
							context.displayMessage("-------您的体力不足，背包里没有食物，自动切换模式------"+msg,Color.ORANGE);
							context.getQqThread().sendMsg("-------您的体力不足，背包里没有食物，自动切换模式------"+msg);
							context.getSendMap().put(4, "#D sw");								
						}
					}							
				}
				/* ------------匹配换鱼饵 分解 ------------**/
				if(msg.contains("条")&&msg.contains("%")&&!msg.contains("%，")
						&&(count%20==10)&&context.getFishHttpService().hasFishEr())
					context.getSendMap().put(4, "#D use er");
				if(count%60==30&&context.getAccount().getTime()!=27&&!context.getAccount().getQq().equals("1799576249"))
					context.getSendMap().put(4, "#D fj all");
				/* ------------匹配卖鱼 -------------**/
				pattern = Pattern.compile(sell);
				matcher = pattern.matcher(msg);
				if(matcher.find()){
					//放东西到保险箱
					if(context.getSendThread().getB()%context.getAccount().getInAll()==2)
						context.getSendMap().put(4, "#D in all");
					else
						context.displayMessage("收到卖鱼消息："+matcher.group(),Color.BLUE);
					//卖鱼命令
					String sendCmd = CmdBean.getSellCmd(matcher.group(),newcmd);
					if(context.getAccount().getTime()==27||context.getAccount().getQq().equals("1799576249"))
						sendCmd += sendCmd.charAt(sendCmd.length()-1);
					context.getSendMap().put(2,sendCmd);
				}
				//时间到暂停
				if(System.currentTimeMillis()>context.getAccount().getStopTime()&&!msg.contains("离开"))
					context.updateStatus(true);
				context.getSendMap().put(1,newcmd);
				//继续发命令，统计计数
				count++;
			}//回复自己的命令结束	
			//暂停后所有清空
			if(context.getAccount().isStop()&&context.getSendMap().size()>0)
				context.getSendMap().clear();
		}
	}
	
	public  boolean isException(String msg) {
		boolean flag = false;
		if(Pattern.matches(error, msg)){
			flag = true;
		}
		String money = "将所有鱼卖出，获得(\\d{1,3})";
		Pattern	pattern = Pattern.compile(money);
		Matcher	matcher = pattern.matcher(msg);
		if(matcher.find()){
			if(matcher.group(1).length()<3)
				flag = true;
		}
		return flag;
	}
	
	public void updateReg() {
		File file = new File("config/RegExp.txt");
		Map<String,Object> jMap = new HashMap<String,Object>();
		Double version = null;
		try {
			if(file.exists()){
				BufferedReader br = new BufferedReader(new FileReader(file));
				String line = null;
				StringBuffer json = new StringBuffer();
				while((line = br.readLine())!=null){
					json.append(line);
				}
				jMap = JSONUtils.parseMap(json.toString());
				version = (Double) jMap.get("version");
				if(version!=null){
					this.next = jMap.get("next").toString();
					this.sell = jMap.get("sell").toString();
					this.error = jMap.get("error").toString();					
				}
				br.close();
			}
			if(version==null){
				jMap.put("next", next);
				jMap.put("sell", sell);
				jMap.put("error", error);
				jMap.put("version", 1.9);
				FileWriter fw = new FileWriter(file);
				fw.write(JSONUtils.toJson(jMap));
				fw.close();				
			}
		} catch (IOException e) {}
	}
}
